<?php
/**
 * Created by PhpStorm.
 * User: Ivanpan
 * Date: 15-1-25
 * Time: 下午5:31
 */
class Helper {
    const COOKIE_KEY = "$%^&*(DUYGBDNDY^FDShfs7）（*&……%sdfds8dfg7ds";
    static $_Bcookie = array ();

    public static function uint($num) {
        return max ( 0, ( int ) $num );
    }

    public static function returnJson(Array $info){
        echo json_encode($info);
        exit();
    }

    /**
     * 设置cookie
     *
     * @author liyang
     *
     * @param string $name
     * @param string $value
     * @param int $expire
     * @param string $path
     * @param string $domain
     *
     */
    public static function setCookie($name, $value, $expire = 0, $path = "/", $domain = '') {
        header ( 'P3P: CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV"' );

        $cookieName = "Boyaa[" . GAMENAME . "][" . PLATFORM . "]";

        $expire = $expire == 0 ? null : time () + $expire;

        setcookie ( $cookieName . "[$name]", $value, $expire, $path, $domain );

        setcookie ( $cookieName . "[{$name}_lock]", md5 ( $value . self::COOKIE_KEY ), $expire, $path, $domain );
    }

    /**
     * 获取cookie
     *
     * @author liyang
     *
     * @param {str} $name
     *
     * @return string null
     */
    public static function getCookie($name) {
        $cookieValue = stripslashes ( $_COOKIE ['Boyaa'] [GAMENAME] [PLATFORM] [$name] );

        if ($_COOKIE ['Boyaa'] [GAMENAME] [PLATFORM] [$name . "_lock"] == md5 ( $cookieValue . self::COOKIE_KEY )) {

            if ($name == 'userInfo') {
                return ( array ) json_decode ( $cookieValue, true );
            } else {
                return $cookieValue;
            }
        }
    }

    /**
     * 删除cookie
     *
     * @author liyang
     *
     * @param {str} $name
     *
     * @return void
     */
    public static function delCookie($name) {
        unset ( $_COOKIE ['Boyaa'] [$name] );
        unset ( $_COOKIE ['Boyaa'] [$name] ['lock'] );

        $nameLock = "Boyaa[" . GAMENAME . "][" . PLATFORM . "][{$name}._lock]";

        setcookie ( $nameLock, '', - 10000 );
        setcookie ( $name, '', - 10000 );
    }


    /**
     * 抓取网页
     *
     * @author sjh
     *
     * @param array $post_data
     *        	post的数据,为空时表示get请求
     * @param string $json
     *        	返回数据格式，0表示json
     *
     * @return string
     */
    static function curl($url, $post_data = array(), $json = 1, $timeout = 20) {
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );

        curl_setopt ( $ch, CURLOPT_TIMEOUT, $timeout );
        curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );

        if (! empty ( $post_data )) {
            curl_setopt ( $ch, CURLOPT_POST, true );
            curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
        }

        $result = curl_exec ( $ch );
        curl_close ( $ch );

        return $data = empty ( $json ) ? $result : json_decode ( $result, true );
    }
    /**
     * 对数组信息进行加密，可以解密回来的
     *
     * @param array $array
     */
    static function makeSigRequest($array) {
        $string = json_encode ( $array );
        return self::authcode ( $string, "Encode" );
    }
    /**
     * 对字符串进行解密
     *
     * @param string $string
     */
    static function getUserInfoBySigRequest($string = '') {
        static $userInfo;
        if (! $userInfo) {
            if ($string == '') {
                $string = $_REQUEST ['sigRequest'];
            }
            $string = self::authcode ( $string );
            $userInfo = json_decode ( $string, true );
        }
        return $userInfo;
    }
    /**
     * 对字符串进行加密，必要的时候，可以解密回来
     *
     * @param {string} $string
     * @param {string} $operation
     *        	DECODE解密 | ENCODE 加密
     * @param {string} $key
     * @param unknown_type $expiry
     */
    static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
        $ckey_length = 4;
        $key = md5 ( $key ? $key : '123456!@###$%^*' );
        $keya = md5 ( substr ( $key, 0, 16 ) );
        $keyb = md5 ( substr ( $key, 16, 16 ) );
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';

        $cryptkey = $keya . md5 ( $keya . $keyc );
        $key_length = strlen ( $cryptkey );

        $string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;
        $string_length = strlen ( $string );

        $result = '';
        $box = range ( 0, 255 );

        $rndkey = array ();
        for($i = 0; $i <= 255; $i ++) {
            $rndkey [$i] = ord ( $cryptkey [$i % $key_length] );
        }

        for($j = $i = 0; $i < 256; $i ++) {
            $j = ($j + $box [$i] + $rndkey [$i]) % 256;
            $tmp = $box [$i];
            $box [$i] = $box [$j];
            $box [$j] = $tmp;
        }

        for($a = $j = $i = 0; $i < $string_length; $i ++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box [$a]) % 256;
            $tmp = $box [$a];
            $box [$a] = $box [$j];
            $box [$j] = $tmp;
            $result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );
        }

        if ($operation == 'DECODE') {
            if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {
                return substr ( $result, 26 );
            } else {
                return '';
            }
        } else {
            return $keyc . str_replace ( '=', '', base64_encode ( $result ) );
        }
    }
    /**
     * 跳转页面
     *
     * @author sjh
     *
     * @param string $url
     * @param string $type
     */
    static function redirect($url, $type = 'html') {
        switch ($type) {
            case 'html' :
                echo '<meta http-equiv="refresh" content="0;url=' . $url . '">';
                break;
            case 'js' :
                echo '<script type="text/javascript">top.location.replace("' . $url . '");</script>';
                break;
        }

        exit ();
    }

    static function json_decode_arr ($str) {
        if (strlen($str) == 0) {
            $res = array();
        }else{
            $res = json_decode($str, true);
        }
        return $res;
    }

    static function json_decode_obj ($str) {
        if (strlen($str) == 0) {
            $res = new stdClass();
        }else{
            $res = json_decode($str);
        }
        return $res;
    }

    static public function getCurTime() {
        //return time()+3600*24*12;
        return time();
    }

    /**
     * 是否中文字符串
     */
    static function validIsCnString($str) {
        return !eregi("[^\x80-\xff]", $str);
    }

}//end-class
